#!/usr/bin/python
# coding:utf-8
__author__ = 'good'
__createday__ = '2015-01-15'
import datetime
import flask
from flask import g
import flask_login
from flask import jsonify
from .. import models
from ..extensions import csrf, db
from . import forms
from golsee.helpers import blog_render
from golsee.decorators import admin_required

#: 展示文章
#: @golsee.cache.cached(timeout=10)
def show(aid):
    article = models.Article.query.get_or_404(aid)
    form = forms.CommentForm()
    article.numlook += 1
    db.session.add(article)
    db.session.commit()
    if form.validate_on_submit() and flask.request.method == 'POST':
        comment = models.Comments(name=form.name.data,
                                  comment=form.comment.data,
                                  article_id=article.id)
        if g.user.is_authenticated():
            comment.author = g.user
        comment.timestamp = datetime.datetime.now()
        db.session.add(comment)
        db.session.commit()
        models.Blog_info.new_comment()
        flask.flash(u'评论成功')
        return flask.redirect(flask.url_for('.show', aid=article.id))
    comments = models.Comments.query.filter_by(article_id=aid).all()
    return blog_render('article/show.html',
                       title=article.title,
                       article=article,
                       form=form,
                       comments=comments)


# ：创建文章
@flask_login.login_required
@admin_required
def create():
    form = forms.ArticleCreateForm()
    form.category_id.choices = models.Category.choices()
    if flask.request.method == 'POST' and form.validate():
        nowtime = datetime.datetime.now()
        article = models.Article(title=form.title.data,
                                 body=form.body.data,
                                 user_id=g.user.id,
                                 category_id=form.category_id.data,
                                 text=flask.request.form.get('textformat'),
                                 timestamp=nowtime,
                                 tag=form.tag.data,
                                 is_open=form.is_open.data)
        article.post_date = nowtime
        db.session.add(article)
        db.session.commit()
        flask.flash(u'文章已创建！')
        models.Blog_info.new_article()
        return flask.redirect(flask.url_for('article.edit', id=article.id))
    return blog_render('article/create.html',
                       title=u'创建文章',
                       form=form)


# ：编辑文章
@csrf.exempt
@flask_login.login_required
@admin_required
def edit(id):
    form = forms.ArticleEditForm()
    form.category_id.choices = models.Category.choices()
    article = models.Article.find_by_id(int(id))
    form.title.data = article.title
    form.body.data = article.body
    form.tag.data = article.tag
    form.category_id.data = article.category_id
    form.is_open.data = article.is_open
    form.id.data = id
    return blog_render('article/edit.html',
                       title=u'编辑' + article.title,
                       form=form)


# ：提交文章
@flask_login.login_required
@admin_required
def commit():
    if g.user.is_admin():
        data = flask.request.form
        title, category, tag, is_open, body, text, art_id = data['title'], data['category'], data['tag'], \
                                                            data['open'], data['body'], data['text'], data["id"]
        if title == '' or tag == '' or body == '' or text == '':
            return jsonify({'msg': u'必填字段不能为空'})
        if art_id:
            article = models.Article.query.get(int(art_id))
            article.title = title
            article.category_id = category
            article.tag = tag
            article.is_open = is_open
            article.body = body
            article.text = text
            article.timestamp = datetime.datetime.now()
            db.session.add(article)
        else:
            nowtime = datetime.datetime.now()
            article = models.Article(title=title,
                                     body=body,
                                     user_id=g.user.id,
                                     category_id=category,
                                     text=text,
                                     timestamp=nowtime,
                                     tag=tag,
                                     is_open=is_open)
            article.post_date = nowtime
        try:
            db.session.add(article)
            db.session.commit()
            return jsonify({'msg': u'保存成功'})
        except:
            return jsonify({'msg': u'保存失败'})
    else:
        return jsonify({'msg': u'请用管理员账号登陆'})
